package org.mybatis.generator.config.xml;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.PropertyHolder;

public class GeneratorConfiguration extends PropertyHolder {

	// xml
	private Document document;
	private XmlElement rootElement;

	private List<XmlElement> contexts = new ArrayList<XmlElement>();

	public GeneratorConfiguration(Properties properties) {
		initXml();
		if (properties == null) {
			properties = System.getProperties();
		}
		GeneratorUtils.addAllProperty(this, properties);
	}

	public GeneratorConfiguration() {
		this(null);
	}

	/**
	 * 生成配置
	 */
	public String genConfiguration() {
		genProperties();
		genClassPathEntry();

		genContext();
		return document.getFormattedContent();
	}

	public void addContext(XmlElement context) {
		if ("context".equalsIgnoreCase(context.getName())) {
			this.contexts.add(context);
		}
	}

	/**
	 * 生成 context
	 */
	private void genContext() {
		if (this.contexts.size() <= 0) {//
			throw new RuntimeException("contexts at least one");
		}
		for (XmlElement context : contexts) {
			rootElement.addElement(context);
		}
	}

	/**
	 * 生成插件 classPathEntry
	 */
	private void genClassPathEntry() {
		XmlElement classPathEntry = new XmlElement("classPathEntry");
		classPathEntry.addAttribute(newAttribute("location"));
		rootElement.addElement(classPathEntry);
	}

	/**
	 * 生成 Properties
	 */
	private void genProperties() {
		XmlElement properties = new XmlElement("properties");
		properties.addAttribute(newAttribute("resource"));
		properties.addAttribute(newAttribute("url"));
		rootElement.addElement(properties);
	}

	/**
	 * 初始化 xml
	 */
	public void initXml() {
		rootElement = new XmlElement("generatorConfiguration");
		document = new Document("-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN",
				"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd");
		document.setRootElement(rootElement);
	}

	/**
	 * 创建属性
	 */
	private Attribute newAttribute(String name) {
		return new Attribute(name, getProperty(name));
	}

	@Override
	public String getProperty(String name) {
		String property = super.getProperty(name);
		return property == null ? "" : property;
	}

	public InputStream getInputStream() {
		return new ByteArrayInputStream(genConfiguration().getBytes());
	}
}
